# Determine if a number is a perfect square or not; compare algorithms
# from: http://www.programminginterviews.info/2011/05/how-to-find-if-number-is-perfect-square.html
# Greg Krol
# Bitbucket.org/GregKrol

import timeit

def isPerfectSquare(num):
    # returns True if num is a perfect square
    # else return False

    num = int(num)

    if (num <= 1):
        return True

    currSquare = 4
    currNum = 2

    while (currSquare <= num):

        if (currSquare == num):
            return True

        currNum += 1
        currSquare = currNum*currNum

    return False

def worstIsPerfectSquare(num):
    # worst implementation to check for the time it takes to solve the perfect square problem
   
    num = int(num)

    for i in range(num):
        if ((i*i) == num):
            return True

    return False

def midIsPerfectSquare(num):
    # OK implemtation, not great, and should not be used
    
    num = int(num) # convert str to int

    num2 = int(num / 2)

    for i in range(num2):
        if ((i*i) == num):
            return True

    return False

def fancyPrint(title,text):
    header =  "==========================\n"
    header += title
    header += "\n--------------------------\n"

    body = text

    footer = "\n==========================\n"

    return header + body + footer

def main():
    text = "This Program will use 3 different algorithms to determine\n"
    text += "if a number is a perfect Square or not\n"

    print(text)

    while(True):
        number = input("Number >")

        #terminate if not a number
        try:
            int(number)
        except ValueError:
            break

        if(isPerfectSquare(number)):
            print(str(number) + " is a perfect square")

            print("The following are the times taken to solve the problem\n")
            
            #worst
            t = timeit.Timer("if(worstIsPerfectSquare("+number+")): break", "from __main__ import worstIsPerfectSquare")
            print(fancyPrint("Worst", str(t.timeit())))

            #mid
            t = timeit.Timer("if(midIsPerfectSquare("+number+")): break", "from __main__ import midIsPerfectSquare")
            print(fancyPrint("Middle Best", str(t.timeit())))

            #best
            t = timeit.Timer("if(isPerfectSquare("+number+")): break", "from __main__ import isPerfectSquare")
            print(fancyPrint("Best", str(t.timeit())))

        else:
            print(str(number) + " is NOT a perfect square")


if __name__ == "__main__":
    main()